﻿using System;
using System.Data;
using DapperExtensions;
using OWE.Core;
using OWE.Core.Data;
using System.Collections.Generic;
using Dapper;

namespace OWE.Data
{
    public class DapperRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly IDbContext _context;

        public DapperRepository(IDbContext context)
        {
            _context = context;
        }

        public T GetById(int id)
        {
            return _context.Connection.Get<T>(id);
        }

        public void Insert(T entity)
        {
            _context.Connection.Insert(entity);
        }

        public void Update(T entity)
        {
            _context.Connection.Update(entity);
        }

        public void Delete(T entity)
        {
            _context.Connection.Delete(entity);
        }

        public IEnumerable<T> GetList()
        {
            IEnumerable<T> list;
            try
            {
                var predicate = Predicates.Field<T>(f => f.Deleted, Operator.Eq, false);
                list = _context.Connection.GetList<T>(predicate);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                _context.Connection.Close();
            }
            return list;
        }


        public IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters)
        {
            IEnumerable<T> list;
            try
            {
                list = _context.Connection.Query<T>(query, parameters.Length == 0 ? null : parameters, null, true, null, CommandType.StoredProcedure);

            }
            catch (Exception ex)
            {
                _context.Connection.Close();
                throw ex;
            }
            finally
            {
                _context.Connection.Close();
            }

            return list;
        }
    }
}
